package com.auction.config;

import com.auction.common.token.TokenTemplate;
import com.auction.common.token.ValidateBean;
import io.swagger.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthConfig implements HandlerInterceptor {

    @Autowired
    TokenTemplate tokenTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取携带的参数
        String auth = request.getHeader("Authorization");

        //设置返回结果提示
        ValidateBean validateBean1 = new ValidateBean();

        //判空
        if (null == auth) {
            validateBean1.setCode(0);
            validateBean1.setMsg("token验证失败");
            resp(response, validateBean1);
            return false;
        }
        //分割字符串·
        String[] tmps = auth.split(" ");
        String tmp = tmps[1];

        //解密
        String token = Base64Utils.encodeToString(tmp.getBytes());

        //进行token验证
        ValidateBean validateBean = tokenTemplate.validToken(token);

        //获取数据
        if (validateBean.getCode() == 1)
            return true;
        else if (validateBean.getCode() == 2) {
            resp(response, validateBean);
            return false;
        } else {
            resp(response, validateBean);
            return false;
        }

    }

    void resp(HttpServletResponse response, ValidateBean validateBean) throws IOException {

        String pretty = Json.pretty(validateBean);
        //设置响应内容的类型和编码
        response.setContentType("application/json;charset=utf-8");
        //获取响应输出流
        try (PrintWriter pw = response.getWriter()) {
            //输出
            pw.write(pretty);
        } catch (IOException e) {
        }

    }
}
